package com.heima.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dto.UserSearchDto;
import com.heima.search.service.ArticleSearchService;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ArticleArticleSearchServiceImpl implements ArticleSearchService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Override
    public ResponseResult search(UserSearchDto dto) throws IOException {
        if (dto == null || StringUtils.isEmpty(dto.getSearchWords())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //请求
        SearchRequest request = new SearchRequest("app_article_info");
        //查询条件
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

        boolQueryBuilder.must(QueryBuilders.multiMatchQuery(dto.getSearchWords(), "title", "content"));
        boolQueryBuilder.filter(QueryBuilders.rangeQuery("publishTime").lt(dto.getMinBehotTime()));
        request.source().query(boolQueryBuilder);
        //根据时间进行倒序排序
        request.source().sort("publishTime", SortOrder.DESC);
        //高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");
        highlightBuilder.preTags("<font style='color:red; font-size: inherit;'>");
        highlightBuilder.postTags("</font>");
        request.source().highlighter(highlightBuilder);
        //分页条件
        request.source().size(10);
        //发送请求
        SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
        //结果解析
        SearchHits hits = response.getHits();
        long total = hits.getTotalHits().value;
        List<Map> articleList = Arrays.stream(hits.getHits()).map(searchHit -> {
            //获取文档数据
            String json = searchHit.getSourceAsString();
            Map map = JSON.parseObject(json, Map.class);
            Map<String, HighlightField> highlightFields = searchHit.getHighlightFields();
            if (!CollectionUtils.isEmpty(highlightFields)) {
                HighlightField field = highlightFields.get("title");
                if (field != null) {
                    Text[] fragments = field.getFragments();
                    map.put("h_title", StringUtils.join(fragments, ","));
                }
            } else {
                map.put("h_title", map.get("title"));
            }
            return map;
        }).collect(Collectors.toList());
        return ResponseResult.okResult(articleList);
    }
}
